package com.toocms.tab.imageload.engine;

import android.content.Context;
import android.net.Uri;

import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.utils.DateUtils;
import com.toocms.tab.configs.FileManager;

import java.io.File;
import java.util.ArrayList;

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;

/**
 * @Description:
 * @Author: Zero
 * @CreateDate: 2023/5/20 16:26
 */
public class CompressEngine implements CompressFileEngine {

    @Override
    public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
        Luban.with(context).load(source).ignoreBy(100)
                .setTargetDir(FileManager.getImageFilePath())
                .setRenameListener(filePath -> {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".0";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }).filter(path -> {
                    if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                        return true;
                    }
                    return !PictureMimeType.isUrlHasGif(path);
                }).setCompressListener(new OnNewCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(String source, File compressFile) {
                        if (call != null)
                            call.onCallback(source, compressFile.getAbsolutePath());
                    }

                    @Override
                    public void onError(String source, Throwable e) {
                        if (call != null) call.onCallback(source, null);
                    }
                }).launch();
    }

    private CompressEngine() {
    }

    private static final class InstanceHolder {
        static final CompressEngine instance = new CompressEngine();
    }

    public static CompressEngine createCompressEngine() {
        return CompressEngine.InstanceHolder.instance;
    }
}
